/*
 * koorz公共部分
 * wordall1101@gmail.com
 * 2013-05-14
 * 世界有我更精彩,相信自己,加油!
 */
(function($) { 
	$.koorz = $.koorz || {
        version: "v1.0.0"
    };
    $.extend($.koorz, {
    	util: {
    		uniqueId:function(){
    		    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    		        var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
    		        return v.toString(16);
    		    });
    		},
    		//判断是否ie6
			isIE6: function() {
				return ($.browser.msie && $.browser.version=="6.0") ? true : false
			},
			trim: function(str) {
				return $.trim(str);
			},
			getStrLength: function(str) {
				str = $.koorz.util.trim(str);
				var theLen = 0,
				strLen = str.replace(/[^\x00-\xff]/g,"**").length;
				theLen = parseInt(strLen/2)==strLen/2 ? strLen/2 : parseInt(strLen/2)+0.5;
				return theLen;
			},
			isEmpty: function(v) {
				return $.koorz.util.trim(v)=="" ? true : false;
			},
	    	submitByEnter : function(e, clk) {
		   		 e = e || window.event;
		   		 var key = e ? (e.charCode || e.keyCode) : 0;
		   		 if(key == 13) {
		   		      clk();
		   		 }
	    	},
	    	getPosition: function(ele){
				var top = ele.offset().top, 
			 	left = ele.offset().left,
				bottom = top + ele.outerHeight(),
				right = left + ele.outerWidth(),
				lmid = left + ele.outerWidth()/2,
				vmid = top + ele.outerHeight()/2;
		
				// iPad position fix
				if (/iPad/i.test(navigator.userAgent)) {
					top -= $(window).scrollTop();
					bottom -= $(window).scrollTop();
					vmid -= $(window).scrollTop();
				}
				var position = {
					leftTop: function(){
						return {x: left, y: top};
					},
					leftMid: function(){
						return {x: left, y: vmid};
					},
					leftBottom: function(){
						return {x: left, y: bottom};
					},
					topMid: function(){
						return {x: lmid, y: top};
					},
					rightTop: function(){
						return {x: right, y: top};
					},
					rightMid: function(){
						return {x: right, y: vmid};
					},
					rightBottom: function(){
						return {x: right, y: bottom};
					},
					midBottom: function(){
						return {x: lmid, y: bottom};
					},
					middle: function(){
						return {x: lmid, y: vmid};
					}
				};			
				return position;
			},
			openWin: function(url){
				var top=190;
				var whichsns = url.substr(url.lastIndexOf("snsType=")+8,1);
				if(whichsns==2){
					var left=document.body.clientWidth>820 ? (document.body.clientWidth-820)/2 : 0;
					window.open(url, 'connect_window', 'height=700, width=820, toolbar=no, menubar=no, scrollbars=yes, resizable=no,top='+top+',left='+left+', location=no, status=no');
				}else if(whichsns==1){
					var left=(document.body.clientWidth-580)/2;
					window.open(url, 'connect_window', 'height=620, width=580, toolbar=no, menubar=no, scrollbars=yes, resizable=no,top='+top+',left='+left+', location=no, status=no');
				}else if(whichsns==0){//新浪登录框
					var left=document.body.clientWidth>900 ? (document.body.clientWidth-900)/2 : 0;
					window.open(url, 'connect_window', 'height=550, width=900, toolbar=no, menubar=no, scrollbars=yes, resizable=no,top='+top+',left='+left+', location=no, status=no');
				}else{
					//renren
					var left=(document.body.clientWidth-580)/2;
					window.open(url, 'connect_window', 'height=420, width=580, toolbar=no, menubar=no, scrollbars=yes, resizable=no,top='+top+',left='+left+', location=no, status=no');
				}
			},
			restrain:function(fn, t){
	    	    var running = false;
	    	    return function(){
	    	        if(running){
	    	        	return;
	    	        }
	    	        running = true;
	    	        fn.apply(null, arguments);
	    	        setTimeout(function(){running = false;}, t);
	    	    };
	    	}
    	}
    });
    $.fn.extend({
    	//返回顶部
    	returntop: function(){
    		if(!this[0]){
				return;
			}
			var backToTopEle = this.click( function() {
				$("html, body").animate({
					scrollTop: 0
				}, 500);
				var topH = $(window).height()+80+"px";
				backToTopEle.data("isClick",true);
				backToTopEle.css("bottom",topH);
			});
			var showEle = function(){
				if(backToTopEle.data("isClick")){
				}else{
					backToTopEle.css({"opacity":1,"bottom":"200px"});
				}
			};
			var timeDelay = null;
			var backToTopFun = function() {	
				var docScrollTop = $(document).scrollTop();
				var winowHeight = $(window).height();
				(docScrollTop > 0)? showEle(): backToTopEle.css({"opacity":0,"bottom":"-200px"}).data("isClick",false);
			};
			$(window).bind("scroll", backToTopFun);
    	},
    	textareaAutoHeight: function(){
    		var obj = this;
    		var h = obj.outerHeight();
			var func = function(){				
				h < 0 && (h = obj.outerHeight());
				if($.browser.mozilla || $.browser.safari){
					obj.height(h);
				}
				var sh = obj[0].scrollHeight,
 				autoHeight = sh < h ? h: sh,
				autoHeight = autoHeight < h * 1.5 ? h: sh;
				obj.height(autoHeight);
			};
			obj.bind("keyup input propertychange focus",func);
    	},
    	textAutoLength: function(options){
    		var settings = {
            	length: 10,
            	tip:"\u8f93\u5165\u5b57\u6570\u8d85\u51fa\u9650\u5236\u8303\u56f4(10)\uff01"
        	};                
        	if(options) {
            	$.extend(settings, options);
        	}
        	
    		var obj = this;
			var func = function(){
				if($.koorz.util.getStrLength(obj.val()) > settings.length){
					$.koorz.tip.show(obj,settings.tip);
				}
			};
			obj.bind("keyup input propertychange focus paste cut keydown blur",func);
    	},
    	wordLimit: function(num){
    		this.each(function(){	
    			if(!num){
    				var copyThis = $(this.cloneNode(true)).hide().css({
    					'position': 'absolute',
    					'width': 'auto',
    					'overflow': 'visible'
    				});
    				$(this).after(copyThis);
    				if(copyThis.width()>$(this).width()){
    					$(this).text($(this).text().substring(0,$(this).text().length-4));
    					$(this).html($(this).html()+'...');
    					copyThis.remove();
    					$(this).wordLimit();
    				}else{
    					copyThis.remove(); //清除复制
    					return;
    				}	
    			}else{
    				var maxwidth=num;
    				if($(this).text().length>maxwidth){
    					$(this).text($(this).text().substring(0,maxwidth));
    					$(this).html($(this).html()+'...');
    				}
    			}					 
    		});
    	},
    	textareaLimit:function(options){
    	    var defaults = {
	            max : 0,
	            callback:function(){}
	        };
	        if(options) {
	            $.extend(defaults, options);
	        };
	        var editor = this;
	        var timer = null ;
	        editor.defaultLength = editor.val().length ;
	        var processChange = function(){
	            var newLength = editor.val().length ;
	            if(defaults.max>0){
	                var num = defaults.max - newLength ;
	                if(num>=0 && num <=10){
	                    defaults.callback(true);
	                    
	                }else if(num<0){
	                    defaults.callback(false);
	                }else{
	                    defaults.callback(true);
	                }
	            }else{
	                
	            }
	            editor.defaultLength = newLength ;
	        };

	        processChange();
	        editor.bind('focus',function(){
	            if(!timer){
	                timer = window.setInterval(function(){
	                    var newLength = editor.val().length ;
	                    if( newLength != editor.defaultLength ){
	                        processChange();
	                    }
	                },10);
	            }
	        });
	        editor.bind('blur', function(){
	            window.clearInterval(timer) ;
	            timer = null;
	        });
	    },
    	dropDown: function(options){
        	var settings = {
            	event: "mouseover",
            	classNm: ".dropdown",
            	active:"active",
            	timer: null,
            	fadeSpeed: 100,
            	duration: 500,
            	offsetX: 82,
            	offsetY: 8,
            	isLocation: false
        	};                
        	if(options) {
            	$.extend(settings, options);
        	}
        	
        	var triggers = this;
            triggers.each(function() {
                $this = $(this);
    			$this.hover(function(){
					clearTimeout(settings.timer);
					var $dropDown = $("."+settings.active);
					$dropDown.removeClass(settings.active);
					$dropDown.fadeOut(settings.fadeSpeed);
					
					$dropDown = $(this).children(settings.classNm);
					$dropDown.addClass(settings.active);
					if(settings.isLocation){
						var position = $.koorz.util.getPosition($(this)).rightBottom();
						$dropDown.css({
							left: position.x - settings.offsetX + "px",
							top: position.y + settings.offsetY + "px"
						});
					}
					$dropDown.fadeIn(settings.fadeSpeed);
				},function(){
					settings.timer = setTimeout(function(){
						var $dropDown = $("."+settings.active);
						$dropDown.removeClass(settings.active);
						$dropDown.fadeOut(settings.fadeSpeed);
					},settings.duration);
				});
			});
    	}
    });
})(jQuery);

/**
 * 获取商品列表
 */
$.koorz.getWaterfall = {
	conf: {
		distance: 250,
		visitNum:0,
		page: 1,
        ajaxUrl: KOORZ.path + "/style/getData",
        ajaxData: {
        	page:1,
        	pageSize:20,
        	cid:'',//分类id
        	lid:''//标签id
        }
    },
    init: function() {
    	var self = $.koorz.getWaterfall;
    	//瀑布流图片初始化
    	$('#goods-wall').masonry({
            itemSelector: '.good-item',
            isFitWidth:true
        });
    	self.ajaxLoad();
		$(window).bind("scroll", self.lazyLoad);
    },
    isLoading: false,
    lazyLoad: function() {
    	var self = $.koorz.getWaterfall;
        var distanceToBottom = $(document).height() - $(window).scrollTop() - $(window).height();
        if (!self.isLoading && distanceToBottom < self.conf.distance) {
        	/*if (self.conf.page == 3){
            	if($.koorz.login.isLogin())return;
            	$(window).bind("scroll", function() {
        	        $("#colorbox").css("top", ($(window).height() - $('#colorbox').outerHeight())/2 + $(document).scrollTop());
        	        $("#colorbox").css("left", ($(window).width() - $('#colorbox').outerWidth())/2);
                });
            }*/
        	if(self.conf.visitNum>=6){
        		$('#goods-wall-pages').show();
                return false;
            }
        	self.ajaxLoad();
        }
    },
    ajaxLoad: function() {
    	var self = $.koorz.getWaterfall,
		conf = $.koorz.getWaterfall.conf;
    	conf.ajaxData.page = conf.page;
        
        $.ajax({
            url: conf.ajaxUrl,
            type: "get",
            dataType: "json",
            timeout: 70000,
            data: conf.ajaxData,
            error: function(XMLHttpRequest, textStatus, errorThrown){
                $('#loading-tips').hide();
            },
            beforeSend:function () {
            	self.isLoading = true;
            	$("#loading-tips").show();
            },
            complete:function () {
            	self.isLoading = false;
                $('#loading-tips').hide();
            },
            success: function(resp) {
            	if(resp.list.length == 0){
            		$(window).unbind("scroll", self.lazyLoad);
            	}else{
            		self.flowGoods(resp.list);
            		conf.page += 1;
            	}
            	conf.visitNum += 1;
            }
        });
    },
    flowGoods: function(list) {
        var items = "";
        $.each(list,function(key,val) {
        	items += '<div class="good-item">';
        	items += '<div class="pic"  style="height:'+val.waterfall_height+'px;" >';
        	items += '<a  href="'+KOORZ.path+'/style/'+val.id+'?type='+val.type+'" target="_blank"> ';
        	items += '<img width="'+val.waterfall_width+'px;" height="'+val.waterfall_height+'px;"' ;
        	items += 'data-original="'+val.waterfall_url+'"/>';
        	items += '</a>';
        	items += '<a href="'+KOORZ.path+'/style/'+val.id+'?type='+val.type+'" class="goods_title_seo">'+val.description+'</a>';
        	items += '</div>';
        	items += '<div class="good-desc-wrap">';
        	items += '<div class="overlay"></div>';
        	items += '<div class="price"><span>￥'+val.price+'</span></div>';
        	items += '<p class="desc">';
        	items += '<a href="'+KOORZ.path+'/style/'+val.id+'?type='+val.type+'" title="'+val.description+'" target="_blank">'+val.description+'</a>';
        	items += '</p>';
        	items += '</div>';
        	items += '</div>';
        });
        var $boxes = $(items);
        $('#goods-wall').append( $boxes ).masonry('appended',$boxes);
        $('#goods-wall').masonry('reload');
        $('img[data-original]').lazyload({effect:'fadeIn',failure_limit:10});
    }
};

/**
 * 获取商品列表
 */
$.koorz.getWaterfall = {
	conf: {
		distance: 250,
		visitNum:0,
		page: 1,
        ajaxUrl: KOORZ.path + "/style/getData",
        ajaxData: {
        	page:1,
        	pageSize:20,
        	cid:'',//分类id
        	lid:''//标签id
        }
    },
    init: function() {
    	var self = $.koorz.getWaterfall;
    	//瀑布流图片初始化
    	$('#goods-wall').masonry({
            itemSelector: '.good-item',
            isFitWidth:true
        });
		
		$(self.conf.page).pagination({
			maxentries:0,
			prev_show_always:false,
			next_show_always:false,
			num_edge_entries: 1,
			num_display_entries: 4,
			items_per_page:2,
			prev_text: "上一页",
			next_text: "下一页",
			ajax:{
				on: true,
	            url:KOORZ.path+"/admin/checkStyle/styles",
	            dataType: 'json',
	            param:function(currentPage,pageSize){
	            	return {
	            		type:self.conf.getType,
	    				page:currentPage+1,
	    				pageSize:2
	        		};
	            },
	            ajaxStart: function(){
	            	$(".styles").empty();
	            	$("#tips").hide();
					$("#loading").show();
	            },
	            callback: function(data) {
	            	$("#loading").hide();
	            	if(data.list.length == 0){
	            		$("#tips").show();
	            	}else {
	            		self.add(data.list);
	            	}
	            }
			}
		});
    },
    isLoading: false,
    lazyLoad: function() {
    	var self = $.koorz.getWaterfall;
        var distanceToBottom = $(document).height() - $(window).scrollTop() - $(window).height();
        if (!self.isLoading && distanceToBottom < self.conf.distance) {
        	/*if (self.conf.page == 3){
            	if($.koorz.login.isLogin())return;
            	$(window).bind("scroll", function() {
        	        $("#colorbox").css("top", ($(window).height() - $('#colorbox').outerHeight())/2 + $(document).scrollTop());
        	        $("#colorbox").css("left", ($(window).width() - $('#colorbox').outerWidth())/2);
                });
            }*/
        	if(self.conf.visitNum>=6){
        		$('#goods-wall-pages').show();
                return false;
            }
        	self.ajaxLoad();
        }
    },
    ajaxLoad: function() {
    	var self = $.koorz.getWaterfall,
		conf = $.koorz.getWaterfall.conf;
    	conf.ajaxData.page = conf.page;
        
        $.ajax({
            url: conf.ajaxUrl,
            type: "get",
            dataType: "json",
            timeout: 70000,
            data: conf.ajaxData,
            error: function(XMLHttpRequest, textStatus, errorThrown){
                $('#loading-tips').hide();
            },
            beforeSend:function () {
            	self.isLoading = true;
            	$("#loading-tips").show();
            },
            complete:function () {
            	self.isLoading = false;
                $('#loading-tips').hide();
            },
            success: function(resp) {
            	if(resp.list.length == 0){
            		$(window).unbind("scroll", self.lazyLoad);
            	}else{
            		self.flowGoods(resp.list);
            		conf.page += 1;
            	}
            	conf.visitNum += 1;
            }
        });
    },
    flowGoods: function(list) {
        var items = "";
        $.each(list,function(key,val) {
        	items += '<div class="good-item">';
        	items += '<div class="pic"  style="height:'+val.waterfall_height+'px;" >';
        	items += '<a  href="'+KOORZ.path+'/style/'+val.id+'?type='+val.type+'" target="_blank"> ';
        	items += '<img width="'+val.waterfall_width+'px;" height="'+val.waterfall_height+'px;"' ;
        	items += 'data-original="'+val.waterfall_url+'"/>';
        	items += '</a>';
        	items += '<a href="'+KOORZ.path+'/style/'+val.id+'?type='+val.type+'" class="goods_title_seo">'+val.description+'</a>';
        	items += '</div>';
        	items += '<div class="good-desc-wrap">';
        	items += '<div class="overlay"></div>';
        	items += '<div class="price"><span>￥'+val.price+'</span></div>';
        	items += '<p class="desc">';
        	items += '<a href="'+KOORZ.path+'/style/'+val.id+'?type='+val.type+'" title="'+val.description+'" target="_blank">'+val.description+'</a>';
        	items += '</p>';
        	items += '</div>';
        	items += '</div>';
        });
        var $boxes = $(items);
        $('#goods-wall').append( $boxes ).masonry('appended',$boxes);
        $('#goods-wall').masonry('reload');
        $('img[data-original]').lazyload({effect:'fadeIn',failure_limit:10});
    }
};

/**
 * 登录
 */
$.koorz.login = {
	init:function(){
		var self = $.koorz.login;
		if(!self.isLogin()){
			$(".singer-wrapper .login").click(function(){
				self.login();
				return false;
			});
		}
	},
	isLogin: function(){
		if($.koorz.util.isEmpty(KOORZ.uid))return false;
		return true;
	},
	login: function(tip,action){
		var toAction = action||"";
		var html = "";
		html += '<div class="login-wrapper bg-white-light">';
		html += '<div class="tip">'+(typeof(tip)=='undefined'?'':tip)+'</div>';
		html += '<div class="login-desc">';
		html += '阅读<a>KOORZ用户协议</a>，使用以下账号直接登录 ';
		html += '</div>';
		html += '<ul class="login-type">';
		html += '<li><a class="sina-weibo-big-icon icon" data-type="0" href='+KOORZ.path+'"/user/login?snsType=0&opt='+toAction+'"><span>新浪微博</span></a></li>';
		html += '<li><a class="qq-weibo-big-icon icon" data-type="1" href='+KOORZ.path+'"/user/login?snsType=1&opt='+toAction+'"><span>腾讯QQ</span></a></li>';
		html += '<li><a class="renren-big-icon icon" data-type="3" href='+KOORZ.path+'"/user/login?snsType=3&opt='+toAction+'"><span>人人网</span></a></li>';
		html += '<li><a class="douban-big-icon icon" data-type="2" href='+KOORZ.path+'"/user/login?snsType=2&opt='+toAction+'"><span>豆瓣网</span></a></li>';
		html += '</ul>';
		html += '</div>';
		
		$.colorbox({html:html,scrolling:false,overlayClose:false,width:"auto",height:"auto",opacity:0.1,speed:400,
			onComplete:function(){
				$(".login-wrapper .login-desc a").click(function(){
					$.koorz.login.agreement();
					return false;
				});
				
				$(".login-wrapper .login-type a").click(function(){
					$.koorz.util.openWin($(this).attr("href"));
					return false;
				});
			},
			onClosed:function(){
				
			}
		});
	},
	agreement: function(){
		$.get(KOORZ.path+"/user/getUserAgreement",function(resp) {
	   		if(resp){
	   			$.colorbox({html:resp,scrolling:false,overlayClose:false,width:"auto",height:"auto",opacity:0.1,speed:400,
					onComplete:function(){
						$(".user-agreement .wrapper").niceScroll({zindex:10000,cursorcolor:"#fc8811",autohidemode:false,
		   					cursorwidth:3,background:"#f0f0f0"});
					},
					onCleanup:function(){
						$(".user-agreement .wrapper").getNiceScroll().hide();
					},
					onClosed:function(){
						if(!$.koorz.login.isLogin()){
							$.koorz.login.login();
						}
					}
				});
	   		}
	    });
	}
};